//
//  GLBottomLineTextView.m
//  GLLibDemo
//
//  Created by huang long on 17/4/26.
//  Copyright © 2017年 历山大亚. All rights reserved.
//

#import "GLBottomLineTextView.h"
#import "NSString+GL.h"


@implementation GLBottomTextView

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    
    NSString *actStr = NSStringFromSelector(action);
    if (_performActions.count > 0) {
        if ([_performActions containsObject:actStr]) {
            return YES;
        }else{
            return NO;
        }
    }else if (_unperformActions.count > 0){
        if ([_unperformActions containsObject:actStr]) {
            return NO;
        }else{
            return YES;
        }
    }else{
        return [super canPerformAction:action withSender:sender];
    }
}


-(void)setPerformActions:(NSArray *)performActions{
    _performActions = performActions;
    _unperformActions = nil;
}

- (void)setUnperformActions:(NSArray *)unperformActions{
    _unperformActions = unperformActions;
    _performActions = nil;
}

@end

@interface GLBottomLineTextView()
{
    UIView *lineView;
    
    BOOL havaText;
    
    CGFloat lastHeight;
}

@end

@implementation GLBottomLineTextView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        CGRect rect = frame;
        rect.size.height = 25;
        self.frame = rect;
        lastHeight = self.frame.size.height;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 4, frame.size.width - 8, 14)];
        [self addSubview:label];
        label.textColor = @"#cccccc".toColor;
        _placeholderLabel = label;
        
        GLBottomTextView *textView = [[GLBottomTextView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 2)];
        textView.delegate = self;
        textView.backgroundColor = [UIColor clearColor];
        textView.textContainerInset = UIEdgeInsetsMake(3, 3, 3, 0);
        [self addSubview:textView];
        _textView = textView;
        //        [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.left.right.top.with.offset(0);
        //            make.bottom.offset(-2);
        //        }];
        
        
        textView.layer.masksToBounds = YES;
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(16, 12, 200, 1)];
        line.backgroundColor = @"#cccccc".toColor;
        [self addSubview:line];
        //        [line mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.left.offset(0);
        //            make.right.offset(0);
        //            make.bottom.offset(0);
        //            make.height.mas_equalTo(1);
        //        }];
        lineView = line;
        
        NSDictionary *dict2 = NSDictionaryOfVariableBindings(lineView);
        line.translatesAutoresizingMaskIntoConstraints = NO;
        NSArray *array3 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[lineView]-|" options:(0) metrics:nil views:dict2];
        NSArray *array4 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[lineView(==1)]-1-|" options:0 metrics:nil views:dict2];
        [self addConstraints:array3];
        [self addConstraints:array4];
        
        
        
        _maxHeight = 84;
    }
    return self;
}


- (instancetype)initWithFrame:(CGRect)frame maxHeight:(CGFloat)maxHeight{
    self = [self initWithFrame:frame];
    if (self) {
        _maxHeight = maxHeight;
    }
    return self;
}

#pragma mark - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([self.delegate respondsToSelector:@selector(glTextViewShouldBeginEditing:)]) {
        return [self.delegate glTextViewShouldBeginEditing:self];
    }
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    lineView.backgroundColor = @"#1567f0".toColor;
    if ([self.delegate respondsToSelector:@selector(glTextViewDidBeginEditing:)]) {
        [self.delegate glTextViewDidBeginEditing:self];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    lineView.backgroundColor = @"#cccccc".toColor;
    if ([self.delegate respondsToSelector:@selector(glTextViewDidEndEditing:)]) {
        [self.delegate glTextViewDidEndEditing:self];
    }
}


- (void)textViewDidChange:(UITextView *)textView{
    
    if (self.maxByteLength > 0) {
        ;
        if (textView.markedTextRange == nil && [textView.text byteLength] > _maxByteLength) {
            textView.text = [textView.text substringToIndex:[textView.text indexWithMaxByteLength:self.maxByteLength]];
            [self textViewDidChange:textView];
            return;
        }
    }
    CGFloat height = [self contentTextViewHeight];
    CGRect frame = self.frame;
    frame.size.height = height;
    CGFloat height2 = height + 20;
    if (self.maxHeight > 0) {
        height2 = MIN(height2, self.maxHeight-2);
    }
    textView.frame = CGRectMake(0, 0, frame.size.width, height2);
    self.frame = frame;
    
    BOOL flag = textView.text.length > 0;
    if (flag && !havaText) {
        _placeholderLabel.hidden = YES;
        if ([self.delegate respondsToSelector:@selector(glTextView:hasText:)]) {
            [self.delegate glTextView:self hasText:NO];
        }
    }else if (!flag && havaText){
        _placeholderLabel.hidden = NO;
        if ([self.delegate respondsToSelector:@selector(glTextView:hasText:)]) {
            [self.delegate glTextView:self hasText:YES];
        }
    }
    if ([self.delegate respondsToSelector:@selector(glTextViewDidChange:)]) {
        [self.delegate glTextViewDidChange:self];
    }
    
    if (lastHeight != self.frame.size.height) {
        if ([self.delegate respondsToSelector:@selector(glTextView:hasChange:)]) {
            [self.delegate glTextView:self hasChange:self.frame.size.height];
        }
        if (textView.contentSize.height <= textView.frame.size.height) {
            //换行是出线了些许问题
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.08 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [textView setContentOffset:CGPointZero animated:YES];
            });
        }
    }
    lastHeight = self.frame.size.height;
    havaText = flag;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //self.height = [self contentTextViewHeight];
    
    if (self.limitEmoji) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString:@"emoji"]) {
            return NO;
        }
#pragma clang diagnostic pop
    }
    if ([self.delegate respondsToSelector:@selector(glTextView:shouldChangeTextInRange:replacementText:)]) {
        return [self.delegate glTextView:self shouldChangeTextInRange:range replacementText:text];
    }
    
    if ([text isEqualToString:@"\n"]) {
        if ([self.delegate respondsToSelector:@selector(glTextViewShouldReturn:)]) {
            return [self.delegate glTextViewShouldReturn:self];
        }
    }else{
        if ([text isEqualToString:@""]) {
            return YES;
        }else{
            if (self.maxByteLength > 0) {
                if ([textView.text byteLength] < self.maxByteLength) {
                    return YES;
                }else{
                    return NO;
                }
            }
        }
    }
    return YES;
}

#pragma mark - private
- (CGFloat)contentTextViewHeight
{
    
    CGFloat height = _textView.contentSize.height + 2;
    
    height = MIN(_maxHeight, height);
    height = MAX(height, 25);
    NSLog(@"height===%f",height);
    return height;
}


#pragma mark - setter
- (void)setLineHide:(BOOL)lineHide{
    _lineHide = lineHide;
    lineView.hidden = lineHide;
}

- (void)setText:(NSString *)text{
    text = text?:@"";
    _textView.text = text;
    [self textViewDidChange:_textView];
}

- (NSString *)text{
    return _textView.text;
}

-(void)setAttributedText:(NSMutableAttributedString *)attributedText{
    _textView.attributedText = attributedText;
    [self textViewDidChange:_textView];
}

- (NSMutableAttributedString *)attributedText{
    return _textView.attributedText.mutableCopy;
}

- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    _placeholderLabel.text = placeholder;
    if (_textView.text.length > 0) {
        _placeholderLabel.hidden = YES;
    }else {
        _placeholderLabel.hidden = NO;
    }
}
-(void)setPlaceholderColor:(UIColor *)placeholderColor{
    _placeholderLabel.textColor = placeholderColor;
}
- (void)setFont:(UIFont *)font{
    _textView.font = font;
    _placeholderLabel.font = font;
}

@end
